<template>
  <!-- 设置房源介绍的模板 -->
  <el-dialog
    :visible.sync="modelPopVisible"
    :close-on-click-modal="false"
    :before-close="handleBeforeClose"
    :append-to-body="true"
    width="70%"
  >
    <span slot="title" class="d-flex ai-baseline">
      <span class="fs-xl" style="margin-left: 8px">{{ title }}</span>
    </span>
    <div>
      <el-tabs v-model="activeName" @tab-click="handleTabChange">
        <template v-for="infoItem in modelInfo">
          <el-tab-pane :label="infoItem.label" :name="infoItem.name" :key="infoItem.name">
            <el-table
              border
              max-height="350px"
              highlight-current-row
              @current-change="handleSelectCurrentChange(infoItem.name, $event)"
              :data="infoItem.data"
              :ref="infoItem.name"
              v-loading="myModelLoading"
            >
              <el-table-column
                v-for="item in infoItem.tableTitles"
                :key="item.title"
                :width="item.width"
                :label="item.title"
              >
                <template slot-scope="{ row }">
                  <i v-if="item.key == 'select'" :class="[row[item.key] ? 'selected' : '', 'select-icon']"></i>

                  <div v-else-if="item.handler">
                    <el-button type="text" @click.stop="item.handler(row)">{{ item.key }}</el-button>
                    <el-button type="text" @click.stop="handleUseModel(row)">使用模板</el-button>
                  </div>
                  <span v-else>{{ row[item.key] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </template>
      </el-tabs>
    </div>

    <!-- <span slot="footer" class="dialog-footer">
      <el-button plain @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handlePopConfirm">确认</el-button>
    </span> -->
  </el-dialog>
</template>

<script>
import { deletedPersonalDefaultInfo, getPersonalDefaultInfo, savePersonalDefaultInfo } from "@/api/user";
import modelTitles from "@/config/model/modelTitle";
import rentModelTitles from "@/config/model/rentModelTitle";
import modelOwnerPsychology from "@/config/model/modelOwnerPsychology";
import modelSellingPoint from "@/config/model/modelSellingPoint";
import rentModelSellingPoint from "@/config/model/rentModelSellingPoint";
import modelServiceIntroduction from "@/config/model/modelServiceIntroduction";
import modelService from "@/config/model/modelService";
import { smoothAsyncHandler } from "@/utils/utilsNew";

const REGS = {
  "{{楼盘名称}}": { key: "resblockName", unit: "" },
  "{{几室}}": { key: "room", unit: "室" },
  "{{几厅}}": { key: "hall", unit: "厅" },
  "{{几卫}}": { key: "toilet", unit: "卫" },
  "{{几厨}}": { key: "cookroom", unit: "厨" },
  "{{几阳台}}": { key: "balcony", unit: "阳台" },
  "{{售价}}": { key: "totalPrices", unit: "万元" },
  "{{建筑面积}}": { key: "buildSize", unit: "平" },
  "{{朝向}}": { key: "direction", unit: "朝向" },
  "{{楼层}}": { key: "floor", unit: "楼" },
  "{{总楼层}}": { key: "totalFloor", unit: "楼" },
  "{{房源年限}}": { key: "houYears", unit: "" },
  "{{装修}}": { key: "decorateType", unit: "" },
};
export default {
  props: {
    title: {
      type: String,
      default: "",
    },
    modelPopVisible: {
      type: Boolean,
      default: false,
    },
    houDelVO: {
      type: Object,
      default() {
        return {};
      }
    },
  },

  data() {
    return {
      isFirstFetch: true,
      activeName: "public",
      currentSelectedId: "",
      myModelLoading: false,
      isHideMineModel: false,
      modelInfo: [
        {
          label: "网络模板",
          name: "public",
          tableTitles: [
            { title: "模板", width: 0, key: "content" },
            {
              title: "操作",
              width: "150",
              key: "添加模板",
              handler: (row) => {
                this.addModel(row);
              },
            },
          ],
          data: [],
        },

        {
          label: "我的模板",
          name: "mine",
          tableTitles: [
            { title: "模板", width: 0, key: "content" },
            {
              title: "操作",
              width: "150",
              key: "移除模板",
              handler: (row) => {
                this.removeModel(row);
              },
            },
          ],
          data: [],
        },
      ],
    };
  },
  watch: {
    activeName(newVal, oldVal) {
      let infoIndex = this.modelInfo.findIndex((v) => v.name == oldVal);
      let data = this.modelInfo[infoIndex].data;
      let oldIndex = data.findIndex((v) => v.id == this.currentSelectedId);

      if (oldIndex > -1 && data[oldIndex].select) {
        this.$refs[oldVal][0].setCurrentRow();

        data[oldIndex].select = false;
        this.$set(data, oldIndex, data[oldIndex]);
        this.currentSelectedId = "";
      }
    },
    modelPopVisible: {
      handler(val) {
        if (!val) {
          this.$refs.public && this.$refs.public[0].setCurrentRow();
          this.$refs.mine && this.$refs.mine[0].setCurrentRow();

          return;
        }
        this.activeName = "public";

        // console.log("初始化。。。。");
        switch (this.title) {
          case "房源标题":
            let titles = this.houDelVO.delegationType == "RENT" ? rentModelTitles : modelTitles;
            this.initModelTitles(titles);
            break;

          case "核心卖点":
            let point = this.houDelVO.delegationType == "RENT" ? rentModelSellingPoint : modelSellingPoint;
            this.initModelTitles(point);
            break;

          case "业主心态":
            this.initModelTitles(modelOwnerPsychology);
            break;

          case "服务介绍":
            this.initModelTitles(modelServiceIntroduction);
            break;

          case "小区配套":
            this.initModelTitles([]);
            break;

          case "税费信息":
            this.initModelTitles(modelService);
            break;

          default:
            break;
        }
      },

      immediate: true,
    },
  },
  created() {},
  mounted() {},

  methods: {
    initModelTitles(list) {
      REGS["{{售价}}"].unit = this.houDelVO.delegationType == "RENT" ? "元" : "万元";

      const keys = Object.keys(REGS);
      let data = list.map((item, i) => {
        let result = item;
        let targetList = keys.filter((v) => !!item.match(v));
        if (targetList.length) {
          result = targetList.reduce((pre, next) => {
            let value = this.houDelVO[REGS[next].key];
            value = value ? value + REGS[next].unit : "";
            return pre.replace(new RegExp(next, "g"), value);
          }, result);
        }

        return {
          id: String(i) + "100",
          content: result,
          select: false,
        };
      });
      this.modelInfo[0].data = data;
    },

    fethModel() {
      this.modelInfo[1].data = [];
      this.myModelLoading = true;

      smoothAsyncHandler(
        getPersonalDefaultInfo({
          tag: this.title,
          page: 1,
          pageSize: 50,
          delegationType: this.houDelVO.delegationType
        })
      ).then(({ isSuccess, content }) => {
        this.myModelLoading = false;
        if (!isSuccess) return;
        this.modelInfo[1].data = content.rows.map((item) => {
          return {
            id: item.id,
            content: item.material,
            select: false,
          };
        });
      });
    },

    addModel(row) {
      savePersonalDefaultInfo({
        tag: this.title,
        material: row.content,
        modelId: row.id,
        delegationType: this.houDelVO.delegationType
      }).then(({ isSuccess, errorMessage = "添加失败！" }) => {
        if (isSuccess) {
          this.$message.success("添加成功！");
        } else {
          this.$message.error(errorMessage);
        }
      });
    },
    removeModel(row) {
      deletedPersonalDefaultInfo({
        tag: this.title,
        id: row.id,
        delegationType: this.houDelVO.delegationType
      }).then(({ isSuccess, content = {} }) => {
        if (isSuccess) {
          let i = this.modelInfo[1].data.findIndex((v) => v.id == row.id);
          this.modelInfo[1].data.splice(i, 1);

          if (row.id == this.currentSelectedId) {
            this.currentSelectedId = "";
          }

          this.$message.success("移除成功！");
        }
      });
    },
    handleClose() {
      this.$emit("update:modelPopVisible", false);
    },
    handlePopConfirm() {
      if (!this.currentSelectedId) {
        return this.$message.error("请先选择模板");
      }

      let data = this.modelInfo.find((v) => v.name == this.activeName).data;
      let item = data.find((v) => v.id == this.currentSelectedId);
      if (item) {
        this.$emit("onsetmodel", item.content);
        this.handleClose();
      }
    },
    handleTabChange(tab) {
      if (tab.name == "mine") {
        this.fethModel();
      }
    },
    handleSelectCurrentChange(name, value) {
      // return console.log({ type, value });
      if (!value) return;
      let infoIndex = this.modelInfo.findIndex((v) => v.name == name);
      let data = this.modelInfo[infoIndex].data;

      let i = data.findIndex((v) => v.id == value.id);

      if (this.currentSelectedId) {
        let oldIndex = data.findIndex((v) => v.id == this.currentSelectedId);
        if (oldIndex > -1) {
          data[oldIndex].select = false;
          this.$set(data, oldIndex, data[oldIndex]);
        }
      }

      data[i].select = true;
      this.$set(data, i, data[i]);
      this.currentSelectedId = data[i].id;
    },

    handleUseModel(row) {
      this.$emit("onsetmodel", row.content);
      this.handleClose();
    },
    handleBeforeClose(done) {
      this.handleClose();
    },
  },
};
</script>

<style lang="scss" scoped>
.select-icon {
  display: inline-block;
  width: 14px;
  height: 14px;
  border: 1px solid #dcdfe6;
  background-color: #ffffff;
  cursor: pointer;
}
.select-icon.selected {
  background-color: #1890ff;
  border-color: #1890ff;
}
</style>
